<template>
	<view class="container">
		<!-- Banner Section -->
		<view class="banner">
		<!-- <image class="logo" src="/static/logo.png"></image> -->
			<text class="headline">联系人备份助手</text>
			<text class="subheadline">安全备份您的通讯录，便捷分享给亲友</text>
		</view>
		
		<!-- Stats Card -->
		<view class="stats-card">
			<view class="stat-item">
				<text class="stat-value">{{contactCount}}</text>
				<text class="stat-label">联系人</text>
			</view>
			<view class="stat-divider"></view>
			<view class="stat-item">
				<text class="stat-value">{{formatTimeDisplay(lastBackupTime) || '无'}}</text>
				<text class="stat-label">上次备份</text>
			</view>
		</view>
		
		<!-- Action Buttons -->
		<view class="action-buttons">
			<button class="btn btn-primary" @click="backupContacts">
				<text class="btn-icon">📱</text>
				<text>一键备份联系人</text>
			</button>
			<button class="btn btn-share" @click="shareBackup" :disabled="!hasBackup">
				<text class="btn-icon">🔗</text>
				<text>分享备份文件</text>
			</button>
		</view>
		
		<!-- Backup History -->
		<view class="history-section" v-if="backupHistory.length > 0">
			<view class="section-header">
				<text class="section-title">备份历史</text>
				<text class="section-action" @click="clearHistory">清空</text>
			</view>
			<view class="history-list">
				<view class="history-item" v-for="(item, index) in backupHistory" :key="index" @click="selectBackup(item)">
					<view class="history-item-left">
						<text class="history-item-title">备份 {{item.count}} 个联系人</text>
						<text class="history-item-time">{{formatTimeDisplay(item.time)}}</text>
					</view>
					<view class="history-item-right">
						<text class="history-item-size">{{item.size}}</text>
						<text class="history-item-icon">〉</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- Tips Section -->
		<view class="tips-section">
			<view class="tip-item">
				<text class="tip-icon">🔒</text>
				<text class="tip-text">本地备份，不上传云端，保障隐私安全</text>
			</view>
			<view class="tip-item">
				<text class="tip-icon">📲</text>
				<text class="tip-text">支持多种格式，兼容安卓和苹果设备</text>
			</view>
			<view class="tip-item">
				<text class="tip-icon">💬</text>
				<text class="tip-text">一键分享至微信、邮箱等应用</text>
			</view>
		</view>
		
		<!-- 备份预览弹窗 -->
		<view class="preview-modal" v-if="showPreview">
			<view class="preview-content">
				<view class="preview-header">
					<text class="preview-title">备份预览</text>
					<text class="preview-close" @click="closePreview">×</text>
				</view>
				<view class="preview-info">
					<text>备份时间: {{previewData.time ? formatTimeDisplay(previewData.time) : ''}}</text>
					<text>联系人数量: {{previewData.contacts ? previewData.contacts.length : 0}} 人</text>
				</view>
				<scroll-view class="preview-list" scroll-y>
					<view class="preview-empty" v-if="!previewData.contacts || previewData.contacts.length === 0">
						<text>未找到联系人数据</text>
					</view>
					<view class="preview-item" v-for="(contact, index) in previewData.contacts" :key="index">
						<text class="preview-item-name">{{contact.displayName || '未命名联系人'}}</text>
						<text class="preview-item-phone" v-for="(phone, phoneIndex) in contact.phoneNumbers" :key="phoneIndex">
							{{phone.value}}
						</text>
					</view>
				</scroll-view>
				<view class="preview-footer">
					<button class="preview-btn" @click="closePreview">关闭</button>
					<button class="preview-btn preview-btn-share" @click="shareCurrentPreview">分享此备份</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				contactCount: 0,
				lastBackupTime: '',
				hasBackup: false,
				backupHistory: [],
				backupInProgress: false,
				// 预览相关
				showPreview: false,
				previewData: {
					time: '',
					contacts: [],
					path: ''
				}
			}
		},
		onLoad() {
			// 获取联系人数量
			this.getContactCount();
			// 获取上次备份时间
			this.getLastBackupInfo();
			// 获取备份历史
			this.getBackupHistory();
		},
		methods: {
			// 获取联系人数量
			getContactCount() {
				// #ifdef APP-PLUS
				if (typeof plus !== 'undefined' && plus.contacts) {
					plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, (addressbook) => {
						// 成功获取通讯录对象
						addressbook.find(['displayName', 'phoneNumbers'], (contacts) => {
							// 更新联系人数量
							this.contactCount = contacts.length;
							console.log('获取到' + contacts.length + '个联系人');
							
							// 缓存联系人数据
							uni.setStorageSync('contactsList', JSON.stringify(contacts));
							uni.setStorageSync('contactsCount', contacts.length);
						}, (err) => {
							// 查找联系人失败
							console.error('查找联系人失败: ' + JSON.stringify(err));
							this.showErrorMessage('查找联系人失败，请检查权限设置');
							this.loadCachedContactsCount();
						});
					}, (err) => {
						// 获取通讯录失败
						console.error('获取通讯录失败: ' + JSON.stringify(err));
						this.showErrorMessage('无法访问通讯录，请检查权限设置');
						this.loadCachedContactsCount();
					});
				} else {
					console.error('plus.contacts API不可用');
					this.showErrorMessage('通讯录API不可用，请确保应用有相应权限');
					this.loadCachedContactsCount();
				}
				// #endif
				
				// #ifndef APP-PLUS
				// 非APP环境下，使用缓存或显示模拟数据
				this.loadCachedContactsCount();
				// #endif
			},
			
			// 加载缓存的联系人数量
			loadCachedContactsCount() {
				try {
					const count = uni.getStorageSync('contactsCount');
					if (count) {
						this.contactCount = count;
					} else {
						// 如果没有缓存，显示默认值
						this.contactCount = 0;
					}
				} catch(e) {
					console.error('读取缓存联系人数量失败', e);
					this.contactCount = 0;
				}
			},
			
			// 显示错误信息
			showErrorMessage(message) {
				uni.showToast({
					title: message,
					icon: 'none',
					duration: 3000
				});
			},
			
			// 获取上次备份信息
			getLastBackupInfo() {
				// 从本地存储获取上次备份时间
				try {
					const lastBackup = uni.getStorageSync('lastBackupTime');
					if (lastBackup) {
						this.lastBackupTime = lastBackup;
						this.hasBackup = true;
					}
				} catch (e) {
					console.error('获取上次备份时间失败', e);
				}
			},
			
			// 获取备份历史
			getBackupHistory() {
				// 从本地存储获取备份历史
				try {
					const history = uni.getStorageSync('backupHistory');
					if (history) {
						this.backupHistory = JSON.parse(history);
					} else {
						// // 模拟数据
						// this.backupHistory = [
						// 	{ time: '2023-10-14 15:30', count: 128, size: '45KB' },
						// 	{ time: '2023-10-01 09:15', count: 125, size: '43KB' }
						// ];
					}
				} catch (e) {
					console.error('获取备份历史失败', e);
				}
			},
			
			// 备份联系人
			backupContacts() {
				if (this.backupInProgress) return;
				this.backupInProgress = true;
				
				// 设置超时保护，避免无限显示"备份中"
				const backupTimeout = setTimeout(() => {
					if (this.backupInProgress) {
						uni.hideLoading();
						this.showErrorMessage('备份操作超时，请重试');
						this.backupInProgress = false;
						console.error('备份操作超时');
					}
				}, 30000); // 30秒超时
				
				uni.showLoading({
					title: '备份中...',
					mask: true
				});
				
				// 每次备份都获取最新的联系人数据
				this.getContactsForBackup(backupTimeout);
			},
			
			// 获取联系人数据用于备份
			getContactsForBackup(backupTimeout) {
				// #ifdef APP-PLUS
				if (typeof plus !== 'undefined' && plus.contacts) {
					plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, (addressbook) => {
						// 成功获取通讯录对象
						addressbook.find(['displayName', 'phoneNumbers'], (contacts) => {
							// 更新联系人数量
							this.contactCount = contacts.length;
							console.log('获取到' + contacts.length + '个联系人用于备份');
							
							// 开始创建备份
							this.createBackupFile(contacts, backupTimeout);
						}, (err) => {
							// 查找联系人失败
							clearTimeout(backupTimeout);
							console.error('查找联系人失败: ' + JSON.stringify(err));
							uni.hideLoading();
							this.showErrorMessage('查找联系人失败，请检查权限设置');
							this.backupInProgress = false;
						});
					}, (err) => {
						// 获取通讯录失败
						clearTimeout(backupTimeout);
						console.error('获取通讯录失败: ' + JSON.stringify(err));
						uni.hideLoading();
						this.showErrorMessage('无法访问通讯录，请检查权限设置');
						this.backupInProgress = false;
					});
				} else {
					clearTimeout(backupTimeout);
					console.error('plus.contacts API不可用');
					uni.hideLoading();
					this.showErrorMessage('通讯录API不可用，请确保应用有相应权限');
					this.backupInProgress = false;
				}
				// #endif
				
				// #ifndef APP-PLUS
				// 非APP环境下
				clearTimeout(backupTimeout);
				uni.hideLoading();
				this.showErrorMessage('当前环境不支持备份联系人');
				this.backupInProgress = false;
				// #endif
			},
			
			// 格式化时间显示
			formatTimeDisplay(timeStr) {
				if (!timeStr) return '';
				
				// 解析时间字符串
				let date;
				try {
					// 尝试直接创建日期对象
					date = new Date(timeStr);
					
					// 检查日期是否有效
					if (isNaN(date.getTime())) {
						// 尝试替换 - 为 /
						date = new Date(timeStr.replace(/-/g, '/'));
					}
					
					// 再次检查日期是否有效
					if (isNaN(date.getTime())) {
						console.error('无法解析日期:', timeStr);
						return timeStr; // 如果解析失败，返回原始字符串
					}
				} catch (e) {
					console.error('日期解析错误:', e);
					return timeStr; // 如果解析出错，返回原始字符串
				}
				
				const now = new Date();
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
				const yesterday = new Date(today);
				yesterday.setDate(yesterday.getDate() - 1);
				
				// 获取时间部分
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const timeFormat = `${hours}:${minutes}`;
				
				// 判断是否是今天
				if (date >= today) {
					return `今天 ${timeFormat}`;
				}
				
				// 判断是否是昨天
				if (date >= yesterday && date < today) {
					return `昨天 ${timeFormat}`;
				}
				
				// 判断是否是今年
				if (date.getFullYear() === now.getFullYear()) {
					const month = (date.getMonth() + 1).toString();
					const day = date.getDate().toString().padStart(2, '0');
					return `${month}月${day}日 ${timeFormat}`;
				}
				
				// 往年的日期
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString();
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}年${month}月${day}日 ${timeFormat}`;
			},
			
			// 创建备份文件
			createBackupFile(contacts, backupTimeout) {
				try {
					// 生成vCard格式的联系人数据
					let vCardData = this.generateVCardData(contacts);
					
					console.log('开始创建备份文件，联系人数量:', contacts.length);
					
					// 判断plus API是否可用
					if (typeof plus === 'undefined' || !plus.io) {
						clearTimeout(backupTimeout);
						uni.hideLoading();
						this.showErrorMessage('文件系统API不可用，请确保应用有相应权限');
						this.backupInProgress = false;
						console.error('plus.io API不可用');
						return;
					}
					
					// 获取应用文档目录
					const fileName = 'contacts_backup_' + new Date().getTime() + '.vcf';
					
					// 使用try-catch包装文件系统操作
					try {
						// 使用更简单的方式写入文件
						const filePath = '_doc/' + fileName; // 相对路径
						const absolutePath = plus.io.convertLocalFileSystemURL(filePath);
						
						console.log('准备写入文件:', filePath);
						
						plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
							console.log('文件系统访问成功');
							
							fs.root.getFile(fileName, { create: true }, (fileEntry) => {
								console.log('文件创建成功');
								
								fileEntry.createWriter((writer) => {
									console.log('文件写入器创建成功');
									
									// 写入成功的回调
									writer.onwrite = () => {
										clearTimeout(backupTimeout);
										console.log('备份文件创建成功：' + absolutePath);
										
										// 更新备份信息
										const now = new Date();
										const timeStr = now.toISOString(); // 使用ISO格式存储时间
										this.lastBackupTime = timeStr;
										this.hasBackup = true;
										
										// 计算文件大小
										const fileSize = this.calculateFileSize(vCardData);
										
										// 保存备份信息到本地存储
										uni.setStorageSync('lastBackupTime', timeStr);
										uni.setStorageSync('lastBackupPath', absolutePath);
										
										// 添加到备份历史
										const newBackup = {
											time: timeStr,
											count: this.contactCount,
											size: fileSize,
											path: absolutePath,
											fileName: fileName
										};
										this.backupHistory.unshift(newBackup);
										
										// 最多保留10条记录
										if (this.backupHistory.length > 10) {
											this.backupHistory = this.backupHistory.slice(0, 10);
										}
										
										// 保存备份历史到本地存储
										uni.setStorageSync('backupHistory', JSON.stringify(this.backupHistory));
										
										uni.hideLoading();
										uni.showToast({
											title: '备份成功',
											icon: 'success'
										});
										
										this.backupInProgress = false;
									};
									
									// 写入错误的回调
									writer.onerror = (e) => {
										clearTimeout(backupTimeout);
										console.error('备份文件创建失败：', e);
										uni.hideLoading();
										this.showErrorMessage('备份文件创建失败: ' + (e.message || '未知错误'));
										this.backupInProgress = false;
									};
									
									// 写入文件内容
									try {
										// 修复: 不使用Blob，直接写入字符串
										writer.write(vCardData);
										console.log('已开始写入文件内容');
									} catch (writeError) {
										clearTimeout(backupTimeout);
										console.error('写入文件内容失败:', writeError);
										uni.hideLoading();
										this.showErrorMessage('写入文件内容失败: ' + (writeError.message || '未知错误'));
										this.backupInProgress = false;
									}
								}, (createWriterError) => {
									clearTimeout(backupTimeout);
									console.error('创建文件写入器失败：', createWriterError);
									uni.hideLoading();
									this.showErrorMessage('创建备份文件失败');
									this.backupInProgress = false;
								});
							}, (getFileError) => {
								clearTimeout(backupTimeout);
								console.error('创建文件失败：', getFileError);
								uni.hideLoading();
								this.showErrorMessage('创建备份文件失败');
								this.backupInProgress = false;
							});
						}, (fsError) => {
							clearTimeout(backupTimeout);
							console.error('访问文件系统失败：', fsError);
							uni.hideLoading();
							this.showErrorMessage('访问文件系统失败');
							this.backupInProgress = false;
						});
					} catch (ioError) {
						clearTimeout(backupTimeout);
						console.error('文件操作异常:', ioError);
						uni.hideLoading();
						this.showErrorMessage('文件操作失败: ' + (ioError.message || '未知错误'));
						this.backupInProgress = false;
					}
				} catch (generalError) {
					clearTimeout(backupTimeout);
					console.error('备份过程中发生异常:', generalError);
					uni.hideLoading();
					this.showErrorMessage('备份过程中发生错误: ' + (generalError.message || '未知错误'));
					this.backupInProgress = false;
				}
			},
			
			// 生成vCard格式数据
			generateVCardData(contacts) {
				let vCardString = '';
				
				contacts.forEach(contact => {
					vCardString += 'BEGIN:VCARD\r\n';
					vCardString += 'VERSION:3.0\r\n';
					
					// 姓名
					if (contact.displayName) {
						vCardString += 'FN:' + contact.displayName + '\r\n';
					}
					
					// 电话号码
					if (contact.phoneNumbers && contact.phoneNumbers.length > 0) {
						contact.phoneNumbers.forEach(phone => {
							if (phone.value) {
								vCardString += 'TEL;TYPE=' + (phone.type || 'CELL') + ':' + phone.value + '\r\n';
							}
						});
					}
					
					vCardString += 'END:VCARD\r\n\r\n';
				});
				
				return vCardString;
			},
			
			// 计算文件大小
			calculateFileSize(data) {
				// 修复: 使用字符串长度计算文件大小
				const bytes = data.length;
				
				if (bytes < 1024) {
					return bytes + 'B';
				} else if (bytes < 1024 * 1024) {
					return (bytes / 1024).toFixed(1) + 'KB';
				} else {
					return (bytes / (1024 * 1024)).toFixed(1) + 'MB';
				}
			},
			
			// 分享备份文件
	shareBackup() {
		if (!this.hasBackup) return;
		
		// 获取最新的备份文件路径
		try {
			const filePath = uni.getStorageSync('lastBackupPath');
			if (!filePath) {
				this.showErrorMessage('未找到备份文件');
				return;
			}
			
			// 上传文件到API
			uni.uploadFile({
				url: 'http://192.168.3.6:5000/api/upload',
				filePath: filePath,
				name: 'file',
				header: {
					'X-API-Key': 'default_secret_key_here'
				},
				success: (uploadRes) => {
					const res = JSON.parse(uploadRes.data);
					if (res.download_url) {
						// 分享下载链接
						plus.share.sendWithSystem({
							type: 'text',
							// content: '联系人备份文件下载链接: ' + res.download_url
							content:  res.download_url
						});
					} else {
						this.showErrorMessage('上传成功但获取下载链接失败');
					}
				},
				fail: (err) => {
					console.error('上传失败:', err);
					this.showErrorMessage('上传备份文件失败');
				}
			});
		} catch(e) {
			console.error('分享失败', e);
			this.showErrorMessage('分享失败，请重试');
		}
	},
			
			// 选择备份文件
			selectBackup(item) {
				uni.showActionSheet({
					itemList: ['预览备份', '分享此备份', '删除此备份'],
					success: (res) => {
						if (res.tapIndex === 0) {
							// 预览此备份
							this.previewBackup(item);
						} else if (res.tapIndex === 1) {
							// 分享此备份
							this.shareSpecificBackup(item);
						} else if (res.tapIndex === 2) {
							// 删除此备份
							this.deleteBackup(item);
						}
					}
				});
			},
			
			// 预览备份
			previewBackup(item) {
				if (!item || !item.path) {
					this.showErrorMessage('备份文件路径无效');
					return;
				}
				
				uni.showLoading({
					title: '加载中...'
				});
				
				// 读取备份文件
				try {
					plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
						// 从文件路径中提取文件名
						const fileName = item.fileName || item.path.substring(item.path.lastIndexOf('/') + 1);
						
						fs.root.getFile(fileName, {}, (fileEntry) => {
							fileEntry.file((file) => {
								const reader = new plus.io.FileReader();
								
								reader.onloadend = (e) => {
									const vCardData = e.target.result;
									// 解析vCard数据
									const contacts = this.parseVCardForPreview(vCardData);
									
									// 设置预览数据
									this.previewData = {
										time: item.time,
										contacts: contacts,
										path: item.path
									};
									
									// 显示预览
									this.showPreview = true;
									uni.hideLoading();
								};
								
								reader.onerror = (e) => {
									console.error('读取文件失败：', e);
									uni.hideLoading();
									this.showErrorMessage('读取备份文件失败');
								};
								
								reader.readAsText(file);
							}, (e) => {
								console.error('获取文件对象失败：', e);
								uni.hideLoading();
								this.showErrorMessage('读取备份文件失败');
							});
						}, (e) => {
							console.error('获取文件失败：', e);
							uni.hideLoading();
							this.showErrorMessage('未找到备份文件');
						});
					}, (e) => {
						console.error('访问文件系统失败：', e);
						uni.hideLoading();
						this.showErrorMessage('访问文件系统失败');
					});
				} catch (e) {
					console.error('预览备份失败', e);
					uni.hideLoading();
					this.showErrorMessage('预览备份失败，请重试');
				}
			},
			
			// 关闭预览
			closePreview() {
				this.showPreview = false;
				this.previewData = {
					time: '',
					contacts: [],
					path: ''
				};
			},
			
			// 解析vCard数据用于预览
			parseVCardForPreview(vCardText) {
				const contacts = [];
				const vcards = vCardText.split('BEGIN:VCARD');
				
				for (let i = 1; i < vcards.length; i++) {
					const vcard = vcards[i];
					if (!vcard || vcard.trim() === '') continue;
					
					const contact = {};
					const lines = vcard.split('\r\n');
					
					// 提取姓名
					const fnMatch = vcard.match(/FN:(.*?)(?:\r\n|$)/);
					if (fnMatch && fnMatch[1]) {
						contact.displayName = fnMatch[1].trim();
					}
					
					// 提取电话号码
					contact.phoneNumbers = [];
					const telRegex = /TEL;TYPE=([^:]+):([^\r\n]+)/g;
					let telMatch;
					
					while ((telMatch = telRegex.exec(vcard)) !== null) {
						contact.phoneNumbers.push({
							type: telMatch[1].trim(),
							value: telMatch[2].trim()
						});
					}
					
					// 如果至少有名字或电话，添加到联系人列表
					if (contact.displayName || (contact.phoneNumbers && contact.phoneNumbers.length > 0)) {
						contacts.push(contact);
					}
				}
				
				return contacts;
			},
			
			// 分享特定备份
			shareSpecificBackup(item) {
				if (!item || !item.path) {
					this.showErrorMessage('备份文件路径无效');
					return;
				}
				
				// 调用系统分享
				plus.share.sendWithSystem({
					type: 'file',
					filePath: item.path,
					title: '联系人备份文件',
					content: '通过联系人备份助手创建的备份文件'
				}, function() {
					console.log('分享成功');
				}, function(e) {
					console.error('分享失败：' + JSON.stringify(e));
				});
			},
			
			// 删除备份
			deleteBackup(item) {
				uni.showModal({
					title: '删除备份',
					content: '确定要删除此备份吗？此操作不可恢复。',
					success: (res) => {
						if (res.confirm) {
							// 如果有文件路径，先删除文件
							if (item.path && item.fileName) {
								plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
									fs.root.getFile(item.fileName, {}, (fileEntry) => {
										fileEntry.remove(() => {
											console.log('文件删除成功');
											this.removeBackupFromHistory(item);
										}, (e) => {
											console.error('删除文件失败：', e);
											// 即使文件删除失败，也从历史记录中移除
											this.removeBackupFromHistory(item);
										});
									}, (e) => {
										console.error('获取文件失败：', e);
										// 如果文件不存在，也从历史记录中移除
										this.removeBackupFromHistory(item);
									});
								}, (e) => {
									console.error('访问文件系统失败：', e);
									this.showErrorMessage('访问文件系统失败');
								});
							} else {
								// 如果没有文件路径，直接从历史记录中移除
								this.removeBackupFromHistory(item);
							}
						}
					}
				});
			},
			
			// 从历史记录中移除备份
			removeBackupFromHistory(item) {
				const index = this.backupHistory.findIndex(i => i.time === item.time);
				if (index !== -1) {
					this.backupHistory.splice(index, 1);
					uni.setStorageSync('backupHistory', JSON.stringify(this.backupHistory));
					
					// 如果删除的是最新的备份，且没有其他备份了
					if (index === 0 && this.backupHistory.length === 0) {
						this.hasBackup = false;
						this.lastBackupTime = '';
						uni.removeStorageSync('lastBackupTime');
						uni.removeStorageSync('lastBackupPath');
					}
					
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					});
				}
			},
			
			// 清空备份历史
			clearHistory() {
				uni.showModal({
					title: '清空历史',
					content: '确定要清空所有备份历史吗？此操作不可恢复。',
					success: (res) => {
						if (res.confirm) {
							// 删除所有备份文件
							this.deleteAllBackupFiles(() => {
								this.backupHistory = [];
								uni.setStorageSync('backupHistory', JSON.stringify(this.backupHistory));
								
								// 清除最后备份信息
								this.hasBackup = false;
								this.lastBackupTime = '';
								uni.removeStorageSync('lastBackupTime');
								uni.removeStorageSync('lastBackupPath');
								
								uni.showToast({
									title: '已清空',
									icon: 'success'
								});
							});
						}
					}
				});
			},
			
			// 删除所有备份文件
			deleteAllBackupFiles(callback) {
				// #ifdef APP-PLUS
				if (this.backupHistory.length > 0) {
					let deletedCount = 0;
					const totalFiles = this.backupHistory.length;
					
					plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
						const processNext = (index) => {
							if (index >= totalFiles) {
								// 所有文件已处理
								if (callback) callback();
								return;
							}
							
							const item = this.backupHistory[index];
							if (item.fileName) {
								fs.root.getFile(item.fileName, {}, (fileEntry) => {
									fileEntry.remove(() => {
										console.log('文件删除成功：' + item.fileName);
										deletedCount++;
										processNext(index + 1);
									}, (e) => {
										console.error('删除文件失败：', e);
										processNext(index + 1);
									});
								}, (e) => {
									console.error('获取文件失败：', e);
									processNext(index + 1);
								});
							} else {
								processNext(index + 1);
							}
						};
						
						// 开始处理
						processNext(0);
					}, (e) => {
						console.error('访问文件系统失败：', e);
						if (callback) callback();
					});
				} else {
					if (callback) callback();
				}
				// #endif
				
				// #ifndef APP-PLUS
				if (callback) callback();
				// #endif
			},
			
			// 分享当前预览的备份
			shareCurrentPreview() {
				if (!this.previewData.path) {
					this.showErrorMessage('备份文件路径无效');
					return;
				}
				
				// 调用系统分享
				plus.share.sendWithSystem({
					type: 'file',
					filePath: this.previewData.path,
					title: '联系人备份文件',
					content: '通过联系人备份助手创建的备份文件'
				}, function() {
					console.log('分享成功');
				}, function(e) {
					console.error('分享失败：' + JSON.stringify(e));
				});
				
				// 关闭预览
				this.closePreview();
			}
		}
	}
</script>

<style>
	.container {
		padding: 40rpx 30rpx;
	}
	
	/* Banner Section */
	.banner {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 40rpx;
	}
	
	.logo {
		height: 140rpx;
		width: 140rpx;
		margin-bottom: 20rpx;
	}
	
	.headline {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
	}
	
	.subheadline {
		font-size: 26rpx;
		color: #666;
		text-align: center;
	}
	
	/* Stats Card */
	.stats-card {
		display: flex;
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		margin-bottom: 40rpx;
		padding: 30rpx 0;
	}
	
	.stat-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.stat-value {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 6rpx;
	}
	
	.stat-label {
		font-size: 24rpx;
		color: #666;
	}
	
	.stat-divider {
		width: 2rpx;
		background-color: #eee;
	}
	
	/* Action Buttons */
	.action-buttons {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-bottom: 40rpx;
	}
	
	.btn {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 90rpx;
		border-radius: 45rpx;
		font-size: 30rpx;
		font-weight: bold;
	}
	
	.btn-icon {
		margin-right: 10rpx;
		font-size: 32rpx;
	}
	
	.btn-primary {
		background-color: #007AFF;
		color: #fff;
	}
	
	.btn-secondary {
		background-color: #F2F2F7;
		color: #333;
	}
	
	.btn-share {
		background-color: #34C759;
		color: #fff;
	}
	
	button[disabled] {
		opacity: 0.6;
	}
	
	/* History Section */
	.history-section {
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		margin-bottom: 40rpx;
		padding: 20rpx;
	}
	
	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx 10rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
		margin-bottom: 10rpx;
	}
	
	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
	}
	
	.section-action {
		font-size: 26rpx;
		color: #007AFF;
	}
	
	.history-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 10rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.history-item:last-child {
		border-bottom: none;
	}
	
	.history-item-left {
		display: flex;
		flex-direction: column;
	}
	
	.history-item-title {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 6rpx;
	}
	
	.history-item-time {
		font-size: 24rpx;
		color: #999;
	}
	
	.history-item-right {
		display: flex;
		align-items: center;
	}
	
	.history-item-size {
		font-size: 24rpx;
		color: #999;
		margin-right: 10rpx;
	}
	
	.history-item-icon {
		color: #ccc;
	}
	
	/* Tips Section */
	.tips-section {
		background-color: #F8F8FA;
		border-radius: 16rpx;
		padding: 20rpx;
	}
	
	.tip-item {
		display: flex;
		align-items: center;
		padding: 16rpx 0;
	}
	
	.tip-icon {
		font-size: 32rpx;
		margin-right: 16rpx;
	}
	
	.tip-text {
		font-size: 26rpx;
		color: #666;
	}
	
	/* 预览模态窗口样式 */
	.preview-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.preview-content {
		width: 90%;
		max-height: 80%;
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
	}
	
	.preview-header {
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #eee;
	}
	
	.preview-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333;
	}
	
	.preview-close {
		font-size: 40rpx;
		color: #999;
		padding: 0 20rpx;
	}
	
	.preview-info {
		padding: 20rpx 30rpx;
		display: flex;
		flex-direction: column;
		gap: 10rpx;
		border-bottom: 1rpx solid #eee;
	}
	
	.preview-info text {
		font-size: 28rpx;
		color: #666;
	}
	
	.preview-list {
		flex: 1;
		max-height: 60vh;
		padding: 0 30rpx;
	}
	
	.preview-empty {
		padding: 40rpx 0;
		text-align: center;
		color: #999;
	}
	
	.preview-item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.preview-item-name {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
		font-weight: bold;
	}
	
	.preview-item-phone {
		font-size: 28rpx;
		color: #666;
		display: block;
		margin-top: 6rpx;
	}
	
	.preview-footer {
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: space-between;
		border-top: 1rpx solid #eee;
	}
	
	.preview-btn {
		flex: 1;
		height: 80rpx;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
		margin: 0 10rpx;
		background-color: #F2F2F7;
		color: #333;
	}
	
	.preview-btn-share {
		background-color: #007AFF;
		color: #fff;
	}
</style>
